package com.wwg.cms.freemarker;

import com.css.framework.container.Container;
import com.css.framework.container.WebContextException;
import com.wwg.cms.util.ReflectUtils;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author 王文磊
 * @version $Id: GetServiceValue.java 16 2010-08-30 07:15:17Z sanshi2 $
 * @date 2010-8-16 16:05:57
 */
public class GetServiceValue implements TemplateMethodModel {
    public Object exec(List arguments) throws TemplateModelException {
        List list = new ArrayList();
//        list.add("dddddddddd");
//        list.add("sssssss");
//        list.add("ggggggggg");
//        for (int i = 0; i < arguments.size(); i++) {
//            Object o = arguments.get(i);
//            System.out.println("o = " + o);
//        }
        String serviceId = (String) arguments.get(0);
        System.out.println("serviceId = " + serviceId);
        String serviceClass = (String) arguments.get(1);
        System.out.println("serviceClass = " + serviceClass);
        String methodName = (String) arguments.get(2);
        System.out.println("methodName = " + methodName);
        int argsize = arguments.size() - 3;
//        aClass=Class.forName(serviceClass==null?serviceid:serviceClass);
        Object serviceImp = null;
        try {
            serviceImp = Container.getBeanFromWeb(serviceId);
        } catch (WebContextException e) {
            if(serviceClass==null || serviceClass.equals(""))serviceClass=serviceId;
            try {
                Class aClass=Class.forName(serviceClass);
                 serviceImp=Container.getServiceFromBroker(serviceId,aClass);
            } catch (ClassNotFoundException e1) {
            }

        }
        if (serviceImp != null) {
            Object[] ars = new Object[argsize];
            for (int i = 0; i < ars.length; i++) {
                ars[i] = arguments.get(i + 3);
            }

            Object ob = ReflectUtils.getServiceValue(serviceImp, methodName, ars);
//            if (ob instanceof List) {
                return ob;
//            } else if (ob instanceof Collection) {
//                list.addAll((Collection) ob);
//            } else if (ob != null) {
//                list.add(ob);
//            }
        }

        return list;
    }
}
